<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8" style="float: right">
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-plus" @click="handleAdd">新增章节</el-button>
      </el-col>
    </el-row>
    <br>
    <el-divider content-position="left">{{train.name}}</el-divider>

    <el-descriptions v-for="(item,index) in course_train_sectionList" :key="item.id" :colon="false" class="margin-top" :title="'第'+(bigWordArr[index])+'章 '+item.name" :column="1" size="small">
      <template slot="extra">
        <el-button-group>
          <el-button type="primary" icon="el-icon-edit" size="small" @click="handleUpdate(item)" plain round>修改章节</el-button>
          <el-button type="success" icon="el-icon-circle-plus-outline" size="small" @click="openWare(item,false)" plain round>添加课件</el-button>
          <el-button type="danger" icon="el-icon-delete" size="small" @click="handleDelete(item,index)" plain round>删除章节</el-button>
        </el-button-group>
      </template>
      <el-descriptions-item>
        <el-table :show-header="false" :data="item.courseWareList" style="width: auto" :fit="false">
          <el-table-column fixed align="center" width="75">
            <template slot-scope="scope">
              <el-button size="medium" icon="el-icon-video-play" @click="openVideo(scope.row)" circle></el-button>
            </template>
          </el-table-column>
          <el-table-column align="center"  width="110">
            <template slot-scope="scope">
              <viewer>
                <el-avatar shape="square" size="large" :src="scope.row.thumbnail"></el-avatar>
              </viewer>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="name" width="300"></el-table-column>
          <el-table-column align="center" label="学习时长管控" width="200">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.studyDurationControl" disabled>  </el-switch>
              <span style="margin-left: 10px">
                {{ scope.row.studyDurationControl ? '已开启' : '已关闭' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="duration" width="300">
            <template slot-scope="scope" width="400">
              <i class="el-icon-alarm-clock">{{scope.row.duration}}</i>
            </template>
          </el-table-column>
          <el-table-column align="right" width="200" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="openWare(scope.row,item.name)">修改课件</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleWareDelete(scope.row)">删除课件</el-button>
<!--                  <el-button size="mini" type="text" icon="el-icon-document-add" @click="handleDelete(scope.row)">添加试题</el-button>-->
            </template>
          </el-table-column>
        </el-table>
      </el-descriptions-item>
    </el-descriptions>
    <!-- 添加或修改培训课程章节表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="课程" prop="trainId">
          <el-input v-model="train.name" readonly/>
        </el-form-item>
        <el-form-item label="章节名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入章节名称"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加课件对话框 -->
    <el-dialog :title="wareForm.sectionName" :visible.sync="wareOpen" width="500px" append-to-body center :destroy-on-close="true">
      <el-form label-position="top" ref="wareform" :model="wareForm" :rules="wareRules" label-width="80px">
        <el-form-item label="课件名称" prop="name">
          <el-input v-model="wareForm.name" placeholder="请输入课件名称" clearable style="width: 250px"/>
        </el-form-item>
        <el-form-item label="学习时长管控" prop="name">
          <el-switch v-model="wareForm.studyDurationControl">
          </el-switch>
        </el-form-item>
        <el-form-item label="视频">
          <el-upload v-loading="wareLoading" class="upload-demo" drag :on-change="fileChange" action="#" :auto-upload="false" multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
          <el-tag v-if="wareForm.video == undefined ||wareForm.video == null || wareForm.video ==''" type="danger">未上传</el-tag>
          <el-tag v-else type="success">已上传 时长：{{wareForm.duration}}</el-tag>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addCourse_ware">确 定</el-button>
        <el-button @click="cancelWare">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 播放视频对话框 -->
    <el-dialog :title="video.name" :visible.sync="videoOpen" append-to-body center fullscreen :destroy-on-close="true">
      <div class="myVideoClass">
        <video-player class="video-player vjs-custom-skin" ref="videoPlayer" @play="onPlayerPlay($event)" :playsinline="true" :options="videoPlayOptions"/>
      </div>
      <div class="myQuestionAndCommentClass">
        <div class="myQuestionClass">
          <el-tag type="success" effect="plain"><i class="el-icon-notebook-2"></i>题目列表</el-tag>
          <el-button type="danger" icon="el-icon-circle-plus" size="mini" @click="openQuestion(false)" style="float: right" plain>添加一条</el-button>
          <el-table v-loading="loading" :data="video.questionList" height="470" size="mini">
            <el-table-column label="内容" prop="content" width="300"/>
            <el-table-column label="题型" width="60">
              <template slot-scope="scope">
                {{scope.row?.type == 0? '单选' : '多选' }}
              </template>
            </el-table-column>
            <el-table-column label="选项" width="540">
              <template slot-scope="scope">
                <template v-for="(item,index) in scope.row?.optionList">
                  <span>{{item.k}}:{{item.v}}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  <br v-if="(index + 1) % 2 === 0">
                </template>
              </template>
            </el-table-column>
            <el-table-column label="答案" width="70">
              <template slot-scope="scope">
                <template v-for="item in scope.row?.answerList">
                  <span>{{item}}</span>
                </template>
              </template>
            </el-table-column>
            <el-table-column label=操作>
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="openQuestion(scope.row)">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="deleteWareQuestion(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="myCommentClass">
          <el-tag effect="plain"><i class="el-icon-chat-dot-square"></i>评论区</el-tag>
          <el-table :data="video.commentList" :show-header="false" style="width: 100%" height="433" size="mini">
            <el-table-column>
              <template slot-scope="scope">
                <div style="float: left;font-size: 14px;font-weight: bold;color: #E6A23C">
                  {{scope.row.userName}}
                </div>
                <div style="float: right">{{dateFormat(scope.row.createTime)}}</div>
                <br>
                <span>
                  {{scope.row.content}}
                </span>
              </template>
            </el-table-column>
          </el-table>
          <el-input placeholder="留下你精彩的评论吧" v-model="comment" class="input-with-select" @keyup.native.enter="sendComment" clearable>
            <el-button v-if="comment != null && comment != ''" slot="append" icon="el-icon-s-promotion" @click="sendComment"></el-button>
          </el-input>
        </div>
      </div>
    <!-- 添加和修改题目弹窗 -->
      <el-dialog :title="question.title" :visible.sync="question.open" width="830px" height="1000px" append-to-body>
        <el-form ref="questionForm" :model="questionForm" :rules="questionRules" label-width="110px">
          <el-form-item label="题型" prop="type">
            <el-radio v-model="questionForm.type" label="0">单选</el-radio>
            <el-radio v-model="questionForm.type" label="1">多选</el-radio>
          </el-form-item>
          <el-form-item label="问题" prop="content">
            <el-input type="textarea" :rows="4" style="width: 500px" v-model="questionForm.content" placeholder="请输入"/>
          </el-form-item>
          <el-form-item label="答案选项(勾选项为答案)" prop="optionList">
            <el-table :data="questionForm?.optionList" style="width: 100%" size="mini" :show-header="false" empty-text="请在下方输入选项添加">
              <el-table-column width="35">
                <template slot-scope="scope"><el-checkbox v-model="scope.row.r" label=""/></template>
              </el-table-column>
              <el-table-column prop="k" width="30"/>
              <el-table-column>
                <template slot-scope="scope">
                  <el-input style="width: 429px" v-model="scope.row.v" size="mini"/>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitQuestionForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script>
import {listCourse_train_section, delCourse_train_section, addCourse_train_section, updateCourse_train_section} from "@/api/course/course_train_section";
import {getCourse_train,} from "@/api/course/course_train";
import {
  addCourse_ware,
  delCourse_ware,
  getCourse_ware,
  addWareQuestion,
  delCourseWareQuestion,
  addWareComment,
  updateCourse_ware,
  upload
} from "@/api/course/course_ware";
import {updateQuestion} from "@/api/ex/question";
import {addStudy} from "@/api/course/record";

export default {
  inject :['reload'],
  name: "Course_train_section",
  data() {
    return {
      bigWordArr: ['一', '二', '三', '四', '五', '六', '七', '八', '九','十','十一','十二','十三','十四','十五','十六','十七','十八','十九'],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 培训课程章节表表格数据
      course_train_sectionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //课程编号
      train: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        trainId: null,
        name: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "章节名称不能为空", trigger: "blur"}
        ],
      },
      questionRules: {
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "选择类型", trigger: "blur" }
        ]
      },
      //评论
      comment:null,
      videoOpen:false,
      video:{},
      wareOpen:false,
      wareLoading:false,
      wareForm:{
        sectionId:'',
        sectionName:'',
        studyDurationControl:false,
      },
      // 表单校验
      wareRules: {
        name: [
          {required: true, message: "课件名称不能为空", trigger: "blur"}
        ],
        video: [
          {required: true, message: "视频不能为空", trigger: "blur"}
        ],
        openType: [
          {required: true, message: "开放类型不能为空", trigger: "change"}
        ],
      },
      //添加题目
      question:{
        open:false,
        title:'',
      },
      questionForm:{},
      //视频播放
      videoPlayOptions : {
        playbackRates: [0.5, 1.0, 1.5, 2.0], //播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:5', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
          type: "video/mp4",
          src: "" //url地址
        }],
        poster: "", //你的封面地址
        // width: document.documentElement.clientWidth,
        notSupportedMessage: '此视频暂无法播放，请稍后再试', //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true  //全屏按钮
        }
      },
    };
  },
  created() {
    var trainId = this.$route.params && this.$route.params.trainId;
    this.train.id = trainId;
    this.queryParams.trainId = trainId;
    this.getList();
    this.getCourseTrain();
  },
  methods: {
    /** 时间格式化 */
    dateFormat(date){
      return new Date(date).toLocaleDateString();
    },
    /** 获取课程 */
    getCourseTrain(){
      getCourse_train(this.train.id).then(response => {
        this.train = response.data;
      });
    },
    /** 查询培训课程章节表列表 */
    getList() {
      this.loading = true;
      listCourse_train_section(this.queryParams).then(response => {
        this.course_train_sectionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        trainId: null,
        name: null,
        reservedOne: null,
        reservedTwo: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加培训课程章节表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = {...row};
      this.open = true;
      this.title = "修改培训课程章节表";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.trainId = this.queryParams.trainId;
          if (this.form.id != null) {
            updateCourse_train_section(this.form).then(response => {
              this.getList();
              this.$modal.msgSuccess("修改成功");
              this.open = false;
            });
          } else {
            addCourse_train_section(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              // this.getList();
              // this.open = false;
              this.reload();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row,index) {
      const ids = row.id;
      this.$modal.confirm('是否确认删除培训课程章节表 "第' + (this.bigWordArr[index]) + '章-'+row.name+ '"的数据项？').then(function () {
        return delCourse_train_section(ids);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
      }).catch(() => {
      });
    },
    //打开视频
    openVideo(row){
      //查询课件
      getCourse_ware(row.id).then(response => {
        //this.video.url = row.video;
        this.videoPlayOptions['sources'][0].src = response.data.video;
        this.video = response.data;
        this.videoOpen = true;
        this.$forceUpdate();
      });
    },
    //打开添加或修改课件对话框
    openWare(row,sectionName){
      this.resetWareForm();
      if(sectionName){
        this.wareForm = {...row};
        this.wareForm.sectionName = sectionName;
      }else{
        this.wareForm.sectionId = row.id;
        this.wareForm.sectionName = row.name;
      }
      this.wareOpen = true;
    },
    //上传文件方法
    fileChange(file,fileList){
      this.wareLoading = true
      //上传文件，获取地址
      upload(file).then(response => {
        this.wareForm.video = response.msg;
        this.wareForm.thumbnail = response.thumbnail;
        this.wareForm.duration = response.duration;
        fileList.splice(1);
        this.wareLoading = false;
      });
    },
    resetWareForm(){
      this.wareForm = {sectionId:'', sectionName:''};
    },
    cancelWare(){
      this.resetWareForm();
      this.wareOpen = false;
      this.wareLoading = false;
    },
    //添加课件
    addCourse_ware(){
      this.$refs["wareform"].validate(valid => {
        if (valid) {
          if (this.wareForm.id != null) {
            updateCourse_ware(this.wareForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              // this.getList();
              // this.cancelWare();
              this.reload();
            });
          } else {
            if (this.wareForm.video == undefined || this.wareForm.video == null || this.wareForm.video == ''){
              this.$modal.msgWarning("请上传视频");
              return;
            }
            this.wareForm.openType = 0;
            addCourse_ware(this.wareForm).then(response => {
              this.getList();
              this.$modal.msgSuccess("新增成功");
              this.cancelWare();
            });
          }
        }
      });
    },
    //删除课件
    /** 删除按钮操作 */
    handleWareDelete(row) {
      this.$modal.confirm(
        '是否确认删除培训课件为"' + row.name + '"的数据项？'
      ).then(function () {return delCourse_ware(row.id);}).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
      }).catch(() => {
      });
    },
    // 打开添加或者修改题目弹窗
    openQuestion(row){
      if(row){
        this.questionForm = JSON.parse(JSON.stringify(row));
        this.question.title = "修改题目"
      }else{
        this.questionForm = {
          optionList:[{k:'A',v:'',r:false}, {k:'B',v:'',r:false}, {k:'C',v:'',r:false}, {k:'D',v:'',r:false}]
        };
        this.question.title = "添加题目"
      }
      this.question.open = true;
    },
    /** 开始播放,添加学习记录 */
    onPlayerPlay(player) {
      addStudy(this.train.id,this.video.id).then(response=>{
        console.log("添加学历记录",response);
      })
    },
    /** 题目提交按钮 */
    submitQuestionForm() {
      this.$refs["questionForm"].validate(valid => {
        if (valid) {
          var flag = 0;
          for (let i = 0; i < this.questionForm.optionList.length; i++) {
            if (this.questionForm.optionList[i].r) flag++;
          }
          if (this.questionForm.type == '0'){//单选
            if (flag!==1){
              this.$modal.msgWarning("单选题，至少或者只需要一个答案");
              return;
            }
          }else{//多选
            if (flag<2){
              this.$modal.msgWarning("多选题，至少需要两个答案");
              return;
            }
          }
          //执行
          if (this.questionForm.id != null) {
            updateQuestion(this.questionForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openVideo(this.video);
              this.questionForm =  {};
              this.question.open = false;
            });
          } else {
            addWareQuestion(this.questionForm,this.video.id).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openVideo(this.video);
              this.questionForm =  {};
              this.question.open = false;
            });
          }
        }
      });
    },
    /** 删除题目 */
    deleteWareQuestion(row){
      this.$modal.confirm('是否确认删除【'+row.content+'】的题目').then(()=>{
        delCourseWareQuestion(this.video.id,row.id).then(() => {
          this.$modal.msgSuccess("删除成功");
          this.openVideo(this.video);
          this.questionForm =  {};
          this.question.open = false;
        })
      }).catch(() => {});
    },
    /** 发表评论 */
    sendComment(){
      if (this.comment == null || this.comment == ''){
        return;
      }
      addWareComment(this.video.id,this.comment).then(response => {
        this.$notify({title: '成功', message: '评论成功', type: 'success'});
        this.openVideo(this.video);
        this.comment = null;
      });
    },
  },
  watch:{
    'video.open': function (n,o){
      if (n === false){
        this.video = {open: false, url:'', name:''}
      }
    }
  }
};
</script>
<style scoped lang="scss">
.myVideoClass{
  object-fit: fill;
  margin: 0 auto;
  width: 1500px;
}
.myQuestionAndCommentClass{
  margin: 0 auto;
  width: 1500px;
  height: 500px;
  //border: solid 1px black;
}
.myQuestionClass{
  margin: 0 auto;
  width: 1100px;
  height: 500px;
  //border: solid 1px red;
  float: left;
}
.myCommentClass{
  margin: 0 auto;
  width: 400px;
  height: 500px;
  //border: solid 1px red;
  float: right;
}
</style>
